#include "libutil.h"
#include "llist.h"
#define ARGMAX 5

int strcmp_new(const void *str1, const void *str2);

void printNode(const void *st);

int main(int argc, char *argv[])
{
   int c1, c2;
   FILE *input, *dict;
   char *usage, *st;
   list_t *list;
   size_t id, len, i;
   usage = "parse_words usage: parse_words -i input_file -d dictionary_file";

   while( (c1 = getopt(argc, argv, ":i:d:")) != -1 )
   {
     switch(c1){
      
       case 'i':
         input = fopen(optarg, "r");
         break;
       case 'd':
         dict = fopen(optarg, "r");
         break;
       case ':':
         fprintf(stderr, "option: %c need a argument!\n", (char)optopt); 
         fprintf(stderr, "%s\n", usage);
         return -1; 
       case '?':
         fprintf(stderr , "Unknown option %c\n", (char)optopt);
         fprintf(stderr, "%s\n", usage);
         return -1;
     }
   } 

   if (argc < ARGMAX )
   {
     fprintf(stderr, "%s\n", usage);
     return -1;
   }
  
   if( input == NULL || dict == NULL )
   {
     fprintf(stderr, "IO error, please check the filename\n");
     return -1;
   }
  
   /*start here*/ 
   c1 = fgetc(input);
   c2 = fgetc(dict);
   if( c1 == EOF || c2 == EOF  )
   {
     fprintf(stderr, "The input file is empty!\n");
     return -1;
   }
   ungetc(c1, input);
   ungetc(c2, dict);

   /*create dict*/
   list = make_empty_list(); 
   while( fscanf(dict, "%d", &len) != EOF )
   {
      st = (char*)safe_malloc(len+1);

      for(i=0; i<len; i++)
      {
        if ( fscanf(dict, "%d", &c1) == EOF )
        {
          fprintf(stderr, "IO error!\n");
          return -1; 
        }
        st[i] = (char)c1;
      }
      st[i] = '\0';
      
      if( insert_at_foot(list, st) == NULL )
      {
        fprintf( stderr, "Fail to insert!\n");
        return -1;
      }
   } 
  
   while( fscanf(input, "%d", &id) != EOF )
   {
       printf("%s", (char*)find_element_by_id(list, id));       
   }

   return 0;
}

/*for test, print node*/
void printNode(const void *st)
{
  printf("%s\n", (char*)st);

}
